#include "../inc/tcpServer.h"
#include "../inc/main.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

/*
 * @brief 获取服务端套接字对应的文件描述符
 * @param in ip 点分十进制形式的ip地址
 * @param in port 主机字节序的端口号
 * @param out socketFileDescribe 服务端套接字对应的文件描述符
 * @return 返回0表示获取成功，其它值未定义
 */
int getSocketFileDescribe(const char *ip, const char *port, int *socketFileDescribe) {
    struct sockaddr_in serverAddress;
    memset(&serverAddress, 0, sizeof serverAddress);
    serverAddress.sin_family = AF_INET;
    serverAddress.sin_addr.s_addr = inet_addr(ip);
    serverAddress.sin_port = htons(atoi(port));

    int tempSocketFileDescribe = socket(AF_INET, SOCK_STREAM, 0);
    // 设置端口可重用
    int reuse = 1;
    setsockopt(tempSocketFileDescribe, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof reuse);
    // 绑定IP和端口号到对应的文件描述符
    bind(tempSocketFileDescribe, (struct sockaddr *)&serverAddress, sizeof serverAddress);
    // 开始监听，等待客户端的连接
    listen(tempSocketFileDescribe, MAX_LISTEN_SIZE);

    // 传出获取的文件描述符
    *socketFileDescribe = tempSocketFileDescribe;
    return 0;
}

/*
 * @brief 通过TCP协议与客户端进行交互
 * @param in serverSocketFileDescribe 服务端套接口对应文件描述符，用于监听客户端请求
 * @param in epollFileDescribe IO多路复用使用的文件描述符
 * @param in pThreadPool 线程池结构体，包含所有线程池
 * @return 返回0表示执行正常
 */
int tcpServer(const int serverSocketFileDescribe, const int epollFileDescribe, threadPool_t *pThreadPool) {
    struct epoll_event event;
    memset(&event, 0, sizeof event);
    event.data.fd = serverSocketFileDescribe;
    event.events = EPOLLIN;

    epoll_ctl(epollFileDescribe, EPOLL_CTL_ADD, serverSocketFileDescribe, &event);
    
    struct epoll_event readyEvents[MAX_READY_EVENT];
    int readyCount = 0;
    int clientFileDescribe = 0;
    while (1) {
        readyCount = epoll_wait(epollFileDescribe, readyEvents, MAX_READY_EVENT, -1);
        for (int i = 0; i < readyCount; i++) {
            if (serverSocketFileDescribe == readyEvents[i].data.fd) {
                clientFileDescribe = accept(serverSocketFileDescribe, NULL, NULL);
                pthread_mutex_lock(&pThreadPool->mutex);
                queuePush(pThreadPool->pThreadQueue, clientFileDescribe);
                pthread_mutex_unlock(&pThreadPool->mutex);
                pthread_cond_signal(&pThreadPool->cond);
            }
        }
    }
    return 0;
}